import { t } from 'i18next'
// import PopupUserWin from './PopupUserWin'
import { Wrap, WrapFooter } from './style'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import { useStore as useMeetingScheduleStore } from '../store'
import { MEETING_JUMP_URL } from '@/utils/constant'
import { MeetingCardProps, MeetingEntity } from '../interface'
import { CommonCard } from './components/common'
import { Button } from '@kedacom/react-next'
import Alert, { confirmModal } from '@/components/Alert'
import { useGlobalStore } from '@/store/global'
import { fetchSetCookie } from '@/api/global'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import { fetchEndMeeting } from '@/api/meetingList'
import shallow from 'zustand/shallow'
/*
export interface MeetingCardProps {
	className?: string
	entity: MeetingEntity
	orderArr: [number, number]
}

组件的使用

{beBegin_held_list.map((meeting: MeetingEntity, index: number) => {
	return (
		<BeBeginHeldCard
			key={index}
			entity={meeting}
			orderArr={[index, beBegin_held_list.length]}
		></BeBeginHeldCard>
	)
})}
*/
export function BeBeginHeldCard(props: MeetingCardProps) {
	const { user, SWITCH } = useGlobalStore(
		(state) => ({
			user: state.user,
			SWITCH: state.SWITCH,
		}),
		shallow
	)
	/*
	useCheckAuthentication 检查身份验证
	*/
	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication()

	const { failure, AjaxFetchBeBeginHeldMeetingList } = useMeetingScheduleStore(
		(state) => ({
			update: state.update,
			/*
			failure 错误处理
			*/
			failure: state.failure,
			/*
			AjaxFetchBeBeginHeldMeetingList 获取正在召开的会议
			*/
			AjaxFetchBeBeginHeldMeetingList: state.AjaxFetchBeBeginHeldMeetingList,
		}),
		shallow
	)
	/*
	getAttendMeetingDesc 根据数据获得参会方式的文字描述
	*/
	const getAttendMeetingDesc = (meeting: MeetingEntity) => {
		/**当前用户是否参会（0-不参加 1-参加）*/
		const is_participated = meeting.current_user_attendee?.is_participated ?? 0
		/**当前用户参会情况（1-去会议室参加 2-通过个人客户端参加 3-电话参会） */
		const participated_type = meeting.current_user_attendee?.participated_type ?? 1
		if (meeting.current_user_attendee) {
			return (
				<>
					{is_participated == 0 && (
						<div className="attending-person-opt">
							<div className="participateType">{t('不参加')}</div>
						</div>
					)}
					{!!is_participated && (
						<div className="attending-person-opt">
							{participated_type === 1 && <div className="participateType">{t('去会议室参加')}</div>}
							{participated_type === 2 && (
								<div className="participateType">{t('通过个人客户端参加')}</div>
							)}
							{participated_type === 3 && <div className="participateType">{t('电话参加')}</div>}
							{participated_type !== 1 && participated_type !== 2 && participated_type !== 3 && ''}
						</div>
					)}
				</>
			)
		}
		return <div className="attending-person-opt"></div>
	}
	/*
	actionconstJoinMeeting点击加入会议按钮
	加入会议
	*/
	const actionconstJoinMeeting = (meeting: MeetingEntity) => {
		/**方法OK*/
		const e164 = meeting.conf_id ?? '' /**e164号 */
		fetchSetCookie(
			{
				meeting_moid: meeting.meeting_id,
				type: 3,
			},
			function () {
				var url = `${window.location.origin}/skyforweb/?roomId=` + e164
				window.open(url, '_blank')
			}
		)
	}
	/*
	handleEndMeeting 结束会议 按钮点击
	结束会议 
	*/
	const handleEndMeeting = (meeting: MeetingEntity) => {
		if (!user?.enable_meeting) {
			Alert(t('无会议管理权限，请通知管理员'))
			return
		}
		checkAuthentication(meeting.meeting_id, (authenticationPassed: boolean) => {
			if (!authenticationPassed) return
			confirmModal({
				msg: <div>{t('您确定要结束该会议吗？')}</div>,
				onOk: async () => {
					const res = await fetchEndMeeting(meeting.meeting_id, 1)
					if (res.success) {
						AjaxFetchBeBeginHeldMeetingList()
					} else {
						failure(res.description || '')
					}
				},
			})
		})
	}
	/*
	handleMeetingManager 会场管理按钮点击 
	进入会场管理
	*/
	const handleMeetingManager = (meeting: MeetingEntity) => {
		if (!user?.enable_meeting) {
			Alert(t('无会议管理权限，请通知管理员'))
			return
		}
		checkAuthentication(meeting.meeting_id, (authenticationPassed: boolean) => {
			if (!authenticationPassed) return
			fetchSetCookie(
				{
					meeting_moid: meeting.meeting_id,
					type: 1,
				},
				() => {
					window.location.href = MEETING_JUMP_URL + '/mcc/manager/' + meeting.meeting_id
				}
			)
		})
	}
	/**获取操作的按钮*/
	const getActionBtn = (meeting: MeetingEntity) => {
		/**会议状态 1-已预订 2-已开始 3-已结束 4-已删除 5-中间临时状态 6-待审批 7-审批不通过 8,9-异常情况*/
		const _state = meeting.state ?? 2
		/**当前用户的moid*/
		const current_user_moid = user?.moid
		/**创建会议用户moid*/
		const create_user_moid = meeting.creator.account
		return (
			<>
				{_state !== 8 && _state !== 9 && (
					<>
						{!!meeting.is_manager_meeting && (
							<Button
								className="btn"
								onClick={() => {
									const user = useGlobalStore.getState().user
									if (!user?.enable_meeting) {
										Alert(t('无会议管理权限，请通知管理员'))
										return false
									}
									handleMeetingManager(meeting)
								}}
							>
								{t('会场管理')}
							</Button>
						)}
						{!!meeting.is_stop && (
							<Button
								className="btn"
								onClick={() => {
									const user = useGlobalStore.getState().user
									if (!user?.enable_meeting) {
										Alert(t('无会议管理权限，请通知管理员'))
										return false
									}
									handleEndMeeting(meeting)
								}}
							>
								{t('结束会议', { context: 'SC1' })}
							</Button>
						)}
						{!!meeting.enable_rtc && !!SWITCH.meetingList.rtcJoin && (
							<Button
								className="btn"
								onClick={() => {
									actionconstJoinMeeting(meeting)
								}}
							>
								{t('加入会议')}
							</Button>
						)}
					</>
				)}
				{(_state === 9 || _state === 8) && (
					<>
						{_state === 8 && <div className="notice">{t('异常恢复中，请稍后刷新。')}</div>}
						{current_user_moid === create_user_moid && (
							<Button
								className="btn"
								onClick={() => {
									const user = useGlobalStore.getState().user
									if (!user?.enable_meeting) {
										Alert(t('无会议管理权限，请通知管理员'))
										return false
									}
									handleEndMeeting(meeting)
								}}
							>
								{t('结束会议', { context: 'SC1' })}
							</Button>
						)}
					</>
				)}
			</>
		)
	}
	return (
		<>
			<Wrap className={props.className}>
				<CommonCard
					entity={props.entity}
					orderArr={props.orderArr}
					is_show_share={true}
					is_show_vcs={true}
					is_show_edit={false}
					is_show_e164={!!props.entity.video}
					is_show_domain_name={true}
					is_upload_file={false}
					file_num={props.entity.file_num ?? 0}
				></CommonCard>
				<WrapFooter className="meeting-card-footer">
					{!!SWITCH.meetingList.attendMethods && <div>{getAttendMeetingDesc(props.entity)}</div>}
					<div className="meeting_card_manager_option">{getActionBtn(props.entity)}</div>
				</WrapFooter>
				<AuthenticationCheck
					open={isAuthenticationOpen}
					setOpen={setIsAuthenticationOpen}
					callBack={successFn}
				/>
			</Wrap>
		</>
	)
}
